#include "../include/mystring.h"

size_t _strlen(const char *s) {
  size_t count = 0;
  for(int i = 0; s[i] != '\0'; ++i, ++count);
  return count;
}

char *_strcpy(char *dst, const char *src) {
  size_t i;
  for(i = 0; src[i] != '\0'; i++)
  {
    dst[i] = src[i];
  }
  dst[i] = '\0';
  return dst;
}

char *_strncpy(char *dst, const char *src, size_t n) {
  for(size_t i = 0; i < n; i++)
  {
    dst[i] = src[i];
  }
  return dst;
}

char *_strcat(char *dst, const char *src) {
  size_t dest_len = _strlen(dst);
  size_t i;
  for(i = 0; src[i] != '\0'; i++)
  {
    dst[dest_len + i] = src[i];
  }
  return dst;
}

int _strcmp(const char *s1, const char *s2) {
  // size_t s1_len = _strlen(s1);
  // size_t s2_len = _strlen(s2);
  size_t i = 0;
  for(; s1[i] != '\0'; i++)
  {
    if(s2[i] == '\0') return s1[i];
    if(s1[i] != s2[i]) return s1[i] - s2[i];
  }
  if(s2[i] != '\0') return s2[i];
  else return 0;
}

int _strncmp(const char *s1, const char *s2, size_t n) {
  // size_t s1_len = _strlen(s1);
  // size_t s2_len = _strlen(s2);
  size_t i = 0;
  for(; i < n && s1[i] != '\0'; i++)
  {
    if(s2[i] == '\0') return s1[i];
    if(s1[i] != s2[i]) return s1[i] - s2[i];
  }
  if(i < n)
  {
    if(s2[i] != '\0') return s2[i];
    else return 0;
  }
  else return 0;
}

void *_memset(void *s, int c, size_t n) {
  char temp = c & 0xFF;
  for(int i = 0; i < n; i++)
  {
    ((char *)s)[i] = temp;
  }
  return s;
}

void *_memmove(void *dst, const void *src, size_t n) {
  char _buf[n];
  const char *srcp = src;
  char *dstp = dst;
  for(int i = 0; i < n; i++)
  {
    _buf[i] = srcp[i];
  }
  for(int i = 0; i < n; i++)
  {
    dstp[i] = _buf[i];
  }
  return dst;
}

void *_memcpy(void *out, const void *in, size_t n) {
  for(int i = 0; i < n; i++)
  {
    ((char *)out)[i] = ((char *)in)[i];
  }
  return out;
}

int _memcmp(const void *s1, const void *s2, size_t n) {
  if(n == 0) return 0;
  size_t i = 0;
  for(; i < n && ((char *)s1)[i] != '\0'; i++)
  {
    if(((char *)s2)[i] == '\0') return ((char *)s1)[i];
    if(((char *)s1)[i] != ((char *)s2)[i]) return ((char *)s1)[i] - ((char *)s2)[i];
  }
  if(i < n)
  {
    if(((char *)s2)[i] != '\0') return ((char *)s2)[i];
    else return 0;
  }
  else return 0;
}
